<template>
  <div class="accessory-management-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入配件名称"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
      <div class="operation-area">
        <el-button type="primary" size="small" @click="handleAdd">新增配件</el-button>
      </div>
    </div>

    <!-- 配件列表表格 -->
    <el-table 
      :data="filteredAccessoryList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
      :expand-row-keys="expandedRows"
      @expand-change="handleExpandChange"
      :row-key="getRowKey"
    >
      <!-- 展开列 -->
      <el-table-column type="expand" width="50px">
        <template slot-scope="props">
          <div class="standard-container">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
              <h4 style="margin: 0; color: #606266;">规格管理</h4>
              <el-button type="primary" size="mini" @click="handleAddStandard(props.row)">新增规格</el-button>
            </div>
            

            
            <!-- 规格列表 -->
            <div v-if="props.row.standards && props.row.standards.length > 0">
              <div v-for="(standard, standardIndex) in props.row.standards" :key="standard.id" class="standard-item">
                <div class="standard-header">
                  <div class="standard-info">
                    <span class="standard-name">{{ standard.standard_name }}</span>
                    <el-button type="text" size="mini" @click="handleEditStandard(standard)">编辑</el-button>
                    <el-button type="text" size="mini" style="color: #F56C6C;" @click="handleDeleteStandard(standard)">删除</el-button>
                  </div>
                  <div class="standard-actions">
                    <el-button type="success" size="mini" @click="handleAddStandardValue(standard)">新增属性值</el-button>
                  </div>
                </div>
                
                <!-- 属性值列表 -->
                <div class="standard-value-list" v-if="standard.values && standard.values.length > 0">
                  <el-table 
                    :data="standard.values" 
                    size="mini"
                    border
                    style="width: 100%; margin-top: 10px;"
                  >
                    <el-table-column label="序号" width="60px" align="center">
                      <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="standard_value" label="属性值" min-width="150px" align="center">
                      <template slot-scope="scope">
                        <span>{{ scope.row.standard_value }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="创建时间" width="150px" align="center">
                      <template slot-scope="scope">
                        <span>{{ formatDate(scope.row.create_time) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px" align="center">
                      <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="handleEditStandardValue(standard, scope.row)">编辑</el-button>
                        <el-button type="text" size="mini" style="color: #F56C6C;" @click="handleDeleteStandardValue(standard, scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                
                <!-- 无属性值提示 -->
                <div v-else class="no-value-tip">
                  <span style="color: #909399; font-size: 12px;">暂无属性值</span>
                </div>
              </div>
            </div>
            
            <!-- 无规格提示 -->
            <div v-else class="no-standard-tip">
              <span style="color: #909399;">暂无规格信息</span>
            </div>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      
      <el-table-column prop="accessory_name" label="配件名称" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.accessory_name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="describe_info" label="描述信息" min-width="200px" align="center">
        <template slot-scope="scope">
          <el-tooltip 
            v-if="scope.row.describe_info" 
            :content="scope.row.describe_info" 
            placement="top" 
            :show-after="500"
            popper-class="describe-tooltip"
          >
            <div class="describe-info-cell">
              <span style="color: #606266;">{{ scope.row.describe_info }}</span>
            </div>
          </el-tooltip>
          <div v-else class="describe-info-cell">
            <span style="color: #c0c4cc;">暂无描述</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column label="创建时间" width="180px" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="更新时间" width="180px" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.update_time) }}</span>
        </template>
      </el-table-column>
      
      <!-- 操作列 -->
      <el-table-column label="操作" width="180px" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑配件弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="form" :rules="formRules" ref="form" label-width="100px">
        <el-form-item label="配件名称" prop="accessory_name">
          <el-input 
            v-model="form.accessory_name" 
            placeholder="请输入配件名称"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="描述信息" prop="describe_info">
          <el-input 
            v-model="form.describe_info" 
            type="textarea"
            :rows="4"
            placeholder="请输入配件描述信息"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑规格弹窗 -->
    <el-dialog
      :title="standardDialogTitle"
      :visible.sync="standardDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="standardForm" :rules="standardFormRules" ref="standardForm" label-width="80px">
        <el-form-item label="规格名称" prop="standard_name">
          <el-input 
            v-model="standardForm.standard_name" 
            placeholder="请输入规格名称"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="standardDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStandardForm" :loading="standardSubmitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑属性值弹窗 -->
    <el-dialog
      :title="standardValueDialogTitle"
      :visible.sync="standardValueDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="standardValueForm" :rules="standardValueFormRules" ref="standardValueForm" label-width="80px">
        <el-form-item label="属性值" prop="standard_value">
          <el-input 
            v-model="standardValueForm.standard_value" 
            placeholder="请输入属性值"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="standardValueDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStandardValueForm" :loading="standardValueSubmitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getAccessoryList, 
  addAccessory, 
  updateAccessory, 
  deleteAccessory,
  addStandard,
  updateStandard,
  deleteStandard,
  addStandardValue,
  updateStandardValue,
  deleteStandardValue,
  getStandardList,
  getStandardValueList
} from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';

export default {
  name: 'AccessoryManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      
      // 表格数据
      accessoryList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增配件',
      isEdit: false,
      submitLoading: false,
      
      // 表单数据
      form: {
        id: '',
        accessory_name: '',
        describe_info: ''
      },
      
      // 表单验证规则
      formRules: {
        accessory_name: [
          { required: true, message: '请输入配件名称', trigger: 'blur' },
          { min: 1, max: 50, message: '配件名称长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      
      // 展开行管理
      expandedRows: [],
      
      // 规格相关
      standardDialogVisible: false,
      standardDialogTitle: '新增规格',
      standardIsEdit: false,
      standardSubmitLoading: false,
      currentAccessory: null,
      
      // 规格表单数据
      standardForm: {
        id: '',
        standard_name: '',
        accessory_id: ''
      },
      
      // 规格表单验证规则
      standardFormRules: {
        standard_name: [
          { required: true, message: '请输入规格名称', trigger: 'blur' },
          { min: 1, max: 50, message: '规格名称长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      
      // 属性值相关
      standardValueDialogVisible: false,
      standardValueDialogTitle: '新增属性值',
      standardValueIsEdit: false,
      standardValueSubmitLoading: false,
      currentStandard: null,
      
      // 属性值表单数据
      standardValueForm: {
        id: '',
        standard_value: '',
        standard_id: ''
      },
      
      // 属性值表单验证规则
      standardValueFormRules: {
        standard_value: [
          { required: true, message: '请输入属性值', trigger: 'blur' },
          { min: 1, max: 50, message: '属性值长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    filteredAccessoryList() {
      return this.accessoryList;
    }
  },
  
  methods: {
    // 获取行键值，确保每行都有唯一标识
    getRowKey(row) {
      return row.id || row.accessory_id || `row_${Math.random()}`;
    },
    
    // 获取配件列表
    async fetchAccessoryList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword
        };
        
        const response = await getAccessoryList(params);
        
        if (response.data.code === 1) {
          this.accessoryList = response.data.data.data || [];
          this.total = response.data.data.total || 0;
          
          // 初始化配件数据，规格数据将在展开行时动态加载
          this.accessoryList.forEach(accessory => {
            // 初始化standards为空数组，等待展开时加载
            this.$set(accessory, 'standards', []);
            console.log(`配件 ${accessory.accessory_name} 初始化完成，等待展开加载规格数据`);
          });
        } else {
          this.$message.error(response.data.msg || '获取配件列表失败');
        }
      } catch (error) {
        console.error('获取配件列表失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('获取配件列表失败');
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchAccessoryList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.currentPage = 1;
      this.fetchAccessoryList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchAccessoryList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchAccessoryList();
    },

    // 新增配件
    handleAdd() {
      this.dialogTitle = '新增配件';
      this.isEdit = false;
      this.form = {
        id: '',
        accessory_name: '',
        describe_info: ''
      };
      this.dialogVisible = true;
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },

    // 编辑配件
    handleEdit(row) {
      this.dialogTitle = '编辑配件';
      this.isEdit = true;
      
      this.form = {
        id: row.id,
        accessory_name: row.accessory_name,
        describe_info: row.describe_info || ''
      };
      this.dialogVisible = true;
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },

    // 删除配件
    async handleDelete(row) {
      try {
        await this.$confirm(`确定要删除配件"${row.accessory_name}"吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await deleteAccessory(row.id);
        
        if (response.data.code === 1) {
          this.$message.success('删除配件成功');
          this.fetchAccessoryList();
        } else {
          this.$message.error(response.data.msg || '删除配件失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除配件失败:', error);
          if (checkTokenFromError(error)) {
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
          } else {
            this.$message.error('删除配件失败');
          }
        }
      }
    },

    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const submitData = {
              accessory_name: this.form.accessory_name.trim(),
              describe_info: this.form.describe_info.trim()
            };

            let response;
            if (this.isEdit) {
              submitData.id = this.form.id;
              response = await updateAccessory(submitData);
            } else {
              response = await addAccessory(submitData);
            }

            if (response.data.code === 1) {
              this.$message.success(this.isEdit ? '编辑配件成功' : '新增配件成功');
              this.dialogVisible = false;
              this.fetchAccessoryList();
            } else {
              this.$message.error(response.data.msg || (this.isEdit ? '编辑配件失败' : '新增配件失败'));
            }
          } catch (error) {
            console.error('提交配件信息失败:', error);
            if (checkTokenFromError(error)) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              this.$message.error('操作失败');
            }
          } finally {
            this.submitLoading = false;
          }
        }
      });
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '-';
      const date = new Date(timestamp * 1000);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 处理展开行变化
    async handleExpandChange(row, expandedRows) {
      this.expandedRows = expandedRows.map(item => item.id);
      
      // 如果展开的是当前行，则获取其规格数据
      if (expandedRows.some(item => item.id === row.id)) {
        console.log(`展开配件行: ${row.accessory_name}`);
        await this.fetchStandardData(row);
      }
    },
    
    // 获取规格数据
    async fetchStandardData(accessory) {
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await getStandardList(accessory.id);
        
        if (response.data.code === 1) {
          // 注意：数据在 msg 字段中，不是 data 字段
          const standards = response.data.msg || [];
          
          // 处理规格数据，将 accessory_standard_value 映射为 values
          const processedStandards = standards.map(standard => ({
            id: standard.id,
            standard_name: standard.standard_name,
            accessory_id: standard.accessory_id,
            values: standard.accessory_standard_value || []
          }));
          
          // 更新本地数据 - 使用Vue.set确保响应式更新
          this.$set(accessory, 'standards', processedStandards);
          console.log(`配件 ${accessory.accessory_name} 刷新后的规格数据:`, processedStandards);
        } else {
          this.$set(accessory, 'standards', []);
          console.log(`配件 ${accessory.accessory_name} 规格数据为空`);
        }
      } catch (error) {
        console.error('获取规格数据失败:', error);
        this.$set(accessory, 'standards', []);
      }
    },
    
    // 新增规格
    handleAddStandard(accessory) {
      this.currentAccessory = accessory;
      this.standardDialogTitle = '新增规格';
      this.standardIsEdit = false;
      
      this.standardForm = {
        id: '',
        standard_name: '',
        accessory_id: accessory.id
      };
      this.standardDialogVisible = true;
      
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.standardForm && this.$refs.standardForm.clearValidate();
      });
    },
    
    // 编辑规格
    handleEditStandard(standard) {
      this.standardDialogTitle = '编辑规格';
      this.standardIsEdit = true;
      
      this.standardForm = {
        id: standard.id,
        standard_name: standard.standard_name,
        accessory_id: standard.accessory_id
      };
      this.standardDialogVisible = true;
      
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.standardForm && this.$refs.standardForm.clearValidate();
      });
    },
    
    // 删除规格
    async handleDeleteStandard(standard) {
      try {
        await this.$confirm(`确定要删除规格"${standard.standard_name}"吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await deleteStandard(standard.id);
        
        if (response.data.code === 1) {
          this.$message.success('删除规格成功');
          // 刷新规格数据
          console.log('删除规格成功，开始刷新数据...');
          const accessory = this.accessoryList.find(item => item.id === standard.accessory_id);
          if (accessory) {
            await this.fetchStandardData(accessory);
            console.log('规格数据刷新完成，当前数据:', accessory.standards);
          }
        } else {
          this.$message.error(response.data.msg || '删除规格失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除规格失败:', error);
          if (checkTokenFromError(error)) {
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
          } else {
            this.$message.error('删除规格失败');
          }
        }
      }
    },
    
    // 提交规格表单
    async submitStandardForm() {
      this.$refs.standardForm.validate(async (valid) => {
        if (valid) {
          this.standardSubmitLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const submitData = {
              standard_name: this.standardForm.standard_name.trim(),
              accessory_id: this.standardForm.accessory_id
            };

            let response;
            if (this.standardIsEdit) {
              submitData.id = this.standardForm.id;
              response = await updateStandard(submitData);
            } else {
              response = await addStandard(submitData);
            }

            if (response.data.code === 1) {
              this.$message.success(this.standardIsEdit ? '编辑规格成功' : '新增规格成功');
              this.standardDialogVisible = false;
              
              // 刷新规格数据
              console.log('操作成功，开始刷新规格数据...');
              await this.fetchStandardData(this.currentAccessory);
              console.log('规格数据刷新完成，当前数据:', this.currentAccessory.standards);
            } else {
              this.$message.error(response.data.msg || (this.standardIsEdit ? '编辑规格失败' : '新增规格失败'));
            }
          } catch (error) {
            console.error('提交规格信息失败:', error);
            if (checkTokenFromError(error)) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              this.$message.error('操作失败');
            }
          } finally {
            this.standardSubmitLoading = false;
          }
        }
      });
    },
    
    // 新增属性值
    handleAddStandardValue(standard) {
      this.currentStandard = standard;
      this.standardValueDialogTitle = '新增属性值';
      this.standardValueIsEdit = false;
      
      this.standardValueForm = {
        id: '',
        standard_value: '',
        standard_id: standard.id
      };
      this.standardValueDialogVisible = true;
      
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.standardValueForm && this.$refs.standardValueForm.clearValidate();
      });
    },
    
    // 编辑属性值
    handleEditStandardValue(standard, value) {
      this.currentStandard = standard;
      this.standardValueDialogTitle = '编辑属性值';
      this.standardValueIsEdit = true;
      
      this.standardValueForm = {
        id: value.id,
        standard_value: value.standard_value,
        standard_id: standard.id
      };
      this.standardValueDialogVisible = true;
      
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.standardValueForm && this.$refs.standardValueForm.clearValidate();
      });
    },
    
    // 删除属性值
    async handleDeleteStandardValue(standard, value) {
      try {
        await this.$confirm(`确定要删除属性值"${value.standard_value}"吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await deleteStandardValue(value.id);
        
        if (response.data.code === 1) {
          this.$message.success('删除属性值成功');
          // 刷新规格数据以获取最新的属性值
          console.log('删除属性值成功，开始刷新数据...');
          const accessory = this.accessoryList.find(item => item.id === standard.accessory_id);
          if (accessory) {
            await this.fetchStandardData(accessory);
            console.log('规格数据刷新完成，当前数据:', accessory.standards);
          }
        } else {
          this.$message.error(response.data.msg || '删除属性值失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除属性值失败:', error);
          if (checkTokenFromError(error)) {
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
          } else {
            this.$message.error('删除属性值失败');
          }
        }
      }
    },
    
    // 提交属性值表单
    async submitStandardValueForm() {
      this.$refs.standardValueForm.validate(async (valid) => {
        if (valid) {
          this.standardValueSubmitLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const submitData = {
              standard_value: this.standardValueForm.standard_value.trim(),
              standard_id: this.standardValueForm.standard_id
            };

            let response;
            if (this.standardValueIsEdit) {
              submitData.id = this.standardValueForm.id;
              response = await updateStandardValue(submitData);
            } else {
              response = await addStandardValue(submitData);
            }

            if (response.data.code === 1) {
              this.$message.success(this.standardValueIsEdit ? '编辑属性值成功' : '新增属性值成功');
              this.standardValueDialogVisible = false;
              
              // 刷新规格数据以获取最新的属性值
              console.log('属性值操作成功，开始刷新规格数据...');
              const accessory = this.accessoryList.find(item => item.id === this.currentStandard.accessory_id);
              if (accessory) {
                await this.fetchStandardData(accessory);
                console.log('规格数据刷新完成，当前数据:', accessory.standards);
              }
            } else {
              this.$message.error(response.data.msg || (this.standardValueIsEdit ? '编辑属性值失败' : '新增属性值失败'));
            }
          } catch (error) {
            console.error('提交属性值信息失败:', error);
            if (checkTokenFromError(error)) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              this.$message.error('操作失败');
            }
          } finally {
            this.standardValueSubmitLoading = false;
          }
        }
      });
    },
  },
  
  created() {
    this.fetchAccessoryList();
  }
};
</script>

<style scoped>
.accessory-management-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式 */
.el-table {
  border: 1px solid #EBEEF5;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}

/* 展开行样式 */
.standard-container {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
  margin: 10px;
}

.standard-item {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 15px;
  padding: 15px;
}

.standard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.standard-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.standard-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.standard-actions {
  display: flex;
  align-items: center;
}

.standard-value-list {
  margin-top: 10px;
}

.no-value-tip {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.no-standard-tip {
  text-align: center;
  padding: 40px;
  color: #909399;
}

/* 描述信息列样式 */
.el-table .describe-info-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-area {
    margin-bottom: 10px;
  }
  
  .operation-area {
    align-self: flex-end;
  }
  
  .standard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .standard-actions {
    align-self: flex-end;
  }
}
</style>

<style>
/* 全局tooltip样式 */
.describe-tooltip {
  max-width: 400px !important;
  word-break: break-all;
  line-height: 1.5;
  font-size: 12px;
  padding: 8px 12px;
}

.describe-tooltip .el-tooltip__popper {
  background-color: #303133;
  color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 